package com.zs.leymovie.fragment;


import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.zs.leymovie.MainActivity;
import com.zs.leymovie.R;
import com.zs.leymovie.activity.MapActivity;
import com.zs.leymovie.activity.YyItemActivity;
import com.zs.leymovie.adapter.YY_PtrAdapter;
import com.zs.leymovie.bean.AppBean;
import com.zs.leymovie.bean.BrandDataEntity;
import com.zs.leymovie.bean.CinemaDataEntity;
import com.zs.leymovie.bean.DataEntity;
import com.zs.leymovie.bean.DistrictDataEntity;
import com.zs.leymovie.bean.SpecialDataEntity;
import com.zs.leymovie.constants.UrlConstants;
import com.zs.leymovie.localcity.ActivitySelectCity;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * 作者：张小冬
 * 时间：2015年8月17日20:53:28
 * 功能：影院-展示当前定位所在地附近的所有影院
 */
public class TheatreFragment extends Fragment implements PullToRefreshBase.OnRefreshListener2, AdapterView.OnItemClickListener {
    @ViewInject(R.id.yy_ptrlistview)
    private PullToRefreshListView ptrListView;
    @ViewInject(R.id.yy_left_location)
    private TextView leftloc_btn;
    @ViewInject(R.id.yy_right_location)
    private ImageView img_loc;
    private YY_PtrAdapter ptrAdapter;
    private List<CinemaDataEntity> lists = new ArrayList<>();
    private List<CinemaDataEntity> selectLists = new ArrayList<>();
    private List<String> distriList = new ArrayList<>();
    private List<String> brandList = new ArrayList<>();
    private List<String> specList = new ArrayList<>();
    private HttpUtils httpUtils;
    private HttpHandler handler;
    private PopupWindow pop;
    @ViewInject(R.id.yy_allarea)
    private TextView allarea;
    @ViewInject(R.id.yy_allpp)
    private TextView allpp;
    @ViewInject(R.id.yy_ts)
    private TextView ts;
    private ListView listView;
    private List<String> popList = new ArrayList<>();
    private ArrayAdapter adapter;
    public static final int REQUEST_CODE = 99;   //请求码
    private String city_id = "159";   //默认显示 深圳
    private String city_name;
    private String movie_id = "";
    private double lng = 114.058000;   //默认深圳
    private double lat = 22.543800;
    private int flag = 1;  //判断三个文本的点击标志
    private boolean isFirst = true;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_theatre, container, false);
        ViewUtils.inject(this, view);

        city_id = ((MainActivity) getActivity()).getCity_id();
        city_name = ((MainActivity) getActivity()).getLngCityName();
        leftloc_btn.setText(((MainActivity) getActivity()).getMovie_name());

        //设置当前电影的id，如果当前不是查询某一个详细的电影，这个可为空
        getMovie_id();

        initView();
        initData(city_id, movie_id);
        return view;
    }

    private void getMovie_id() {
        if (((MainActivity) getActivity()).getMovie_id() != null && ((MainActivity) getActivity()).getMovie_id().length() > 0) {
            movie_id = ((MainActivity) getActivity()).getMovie_id();
        }
    }

    private void initData(String cityid, String movie_id) {
        handler = httpUtils.send(HttpRequest.HttpMethod.GET, UrlConstants.getYY_URL(cityid, movie_id), new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                ptrListView.onRefreshComplete();
                String result = responseInfo.result;
                AppBean app = JSONObject.parseObject(result, AppBean.class);
                if (app.getStatus() == 1) {   //成功
                    DataEntity data = app.getData();
                    if (data != null) {           //获取当前影院信息
                        List<CinemaDataEntity> tempcine = data.getCinema_data();
                        if (tempcine != null && tempcine.size() > 0) {
                            if (lists != null) {
                                lists.clear();
                            }
                            lists.addAll(tempcine);
                            if (isFirst && lists.size() > 0) {
                                selectLists.clear();
                                selectLists.addAll(lists);
                                isFirst = false;
                            }
                            ptrAdapter.notifyDataSetChanged();
                        }

                        List<DistrictDataEntity> tempdis = data.getDistrict_data();  //区域
                        if (tempdis != null && tempdis.size() > 0) {
                            if (distriList != null) {
                                distriList.clear();     //更新前清除
                                distriList.add("全部城区");    //1
                            }
                            for (int i = 0; i < tempdis.size(); i++) {
                                distriList.add(tempdis.get(i).getName());
                            }
                        }

                        List<BrandDataEntity> tempbra = data.getBrand_data();     //品牌
                        if (tempbra != null && tempbra.size() > 0) {
                            if (brandList != null) {
                                brandList.clear();
                                brandList.add("全部品牌");     //2
                            }
                            for (int i = 0; i < tempbra.size(); i++) {
                                brandList.add(tempbra.get(i).getName());
                            }
                        }

                        List<SpecialDataEntity> tempspe = data.getSpecial_data();  //特色
                        if (tempspe != null && tempspe.size() > 0) {
                            if (specList != null) {
                                specList.clear();
                                specList.add("特色筛选");      //3
                            }
                            for (int i = 0; i < tempspe.size(); i++) {
                                specList.add(tempspe.get(i).getName());
                            }
                        }
                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                ptrListView.onRefreshComplete();
                Toast.makeText(getActivity(), "数据加载失败，请稍候再试", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void initView() {
        httpUtils = new HttpUtils();
        ptrListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        ptrListView.setOnRefreshListener(this);
        ptrAdapter = new YY_PtrAdapter(lists, getActivity());
        ptrListView.setAdapter(ptrAdapter);
        ptrListView.setOnItemClickListener(this);
        ptrListView.setRefreshing();

        final View popView = LayoutInflater.from(getActivity()).inflate(R.layout.pop_listview, null);
        listView = (ListView) popView.findViewById(R.id.pop_list);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {    //poplist的点击事件
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView tv = (TextView) view.findViewById(R.id.pop_item_text);
                String str = tv.getText().toString();
                if (flag == 1) {
                    allarea.setText(str);
                    str = str.substring(0, str.length() - 1);   //去掉区
                } else if (flag == 2) {
                    allpp.setText(str);
                } else {
                    ts.setText(str);
                }
                if (!(tv.getText().toString().equals("全部城区"))) {
                    lists.clear();
                    for (int i = 0; i < selectLists.size(); i++) {
                        CinemaDataEntity data = selectLists.get(i);
                        if (data.getName().contains(str) || data.getAddress().contains(str)) {
                            lists.add(data);
                        }
                    }
                }else{
                    lists.addAll(selectLists);
                }
                    ptrAdapter.notifyDataSetChanged();
                    pop.dismiss();
            }
        });

        adapter = new ArrayAdapter(getActivity(), R.layout.yy_headpop_item, popList);    //设置pop适配器
        listView.setAdapter(adapter);
        pop = new PopupWindow(popView);
        pop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        pop.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        //pop.setFocusable(true);
        pop.setBackgroundDrawable(new ColorDrawable(Color.WHITE)); //设置背景后点击外部不能让它消失，跟下面的冲突activity
    }

    /**
     * 跳转到选择城市定位界面
     *
     * @param view
     */
    @OnClick({R.id.yy_allarea, R.id.yy_allpp, R.id.yy_ts, R.id.yy_left_location, R.id.yy_right_location})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.yy_left_location:
                Intent intent = new Intent(getActivity(), ActivitySelectCity.class);
                startActivityForResult(intent, REQUEST_CODE);     //开始一个activity，并把结果返回
                allarea.setText("全部城区");
                allpp.setText("全部品牌");
                ts.setText("特色筛选");
                isFirst = true;
                break;
            case R.id.yy_allarea:
                flag = 1;
                clear();
                popList.addAll(distriList);
                break;
            case R.id.yy_allpp:
                clear();
                flag = 2;
                popList.addAll(brandList);
                break;
            case R.id.yy_ts:
                clear();
                flag = 3;
                popList.addAll(specList);
                break;
            case R.id.yy_right_location:
                Intent mapIntent = new Intent(getActivity(), MapActivity.class);   //跳转到显示地图的activity
                mapIntent.putExtra("lng", lng);
                mapIntent.putExtra("lat", lat);
                startActivity(mapIntent);
                break;
        }
        adapter.notifyDataSetChanged();
    }

    public void clear() {
        if (popList != null) {     //清除之前的数据
            popList.clear();
        }
        if (!pop.isShowing()) {
            //popList.add(0,"显示全部");
            pop.showAsDropDown(allpp);   //显示
        } else {
            pop.dismiss();               //消失
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == REQUEST_CODE) {
            Bundle bundle = data.getExtras();
            leftloc_btn.setText(bundle.getString("lngCityName"));  //得到城市名
            city_id = bundle.getString("cityid");                  //城市编号

            ((MainActivity) getActivity()).setCity_id(city_id);
            ((MainActivity) getActivity()).setLngCityName(bundle.getString("lngCityName"));

            lat = bundle.getDouble("lat", 22.543800);                  //得到伟度，默认深圳
            lng = bundle.getDouble("lng", 114.058000);                 //得到经度，默认深圳
            initData(city_id, movie_id);   //重新定位
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        initData(city_id, movie_id);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (handler != null) {
            handler.cancel();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        leftloc_btn.setText(((MainActivity) getActivity()).getLngCityName());
        getMovie_id();
        if (!TextUtils.equals(city_id, ((MainActivity) getActivity()).getCity_id())) {
            city_id = ((MainActivity) getActivity()).getCity_id();
            initData(city_id, movie_id);
        }
    }

    /**
     * ptrlistview的点击事件
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (pop != null) {
            pop.dismiss();
        }
        //启动另一个activity
        Intent intent = new Intent(getActivity(), YyItemActivity.class);
        CinemaDataEntity entity = lists.get(position - 1);
        intent.putExtra("cimeadata", entity);  //电影院的ID
        intent.putExtra("cityid", city_id);     //城市ID
        startActivity(intent);
    }
}
